// ==UserScript==
// @name         全局变量管理器
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  提供全局字符串变量管理功能，支持持久化存储和可视化编辑
// @author       You
// @match        *://*/*
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_addStyle
// ==/UserScript==

(function() {
    'use strict';

    // 检测是否在Tampermonkey环境中
    const isTampermonkey = typeof GM_getValue !== 'undefined' && typeof GM_setValue !== 'undefined';
    
    // 备用存储方案（使用localStorage）
    const fallbackStorage = {
        get(key, defaultValue = '') {
            try {
                const value = localStorage.getItem(`global_var_${key}`);
                return value !== null ? value : defaultValue;
            } catch (error) {
                console.error(`localStorage获取失败: ${error.message}`);
                return defaultValue;
            }
        },
        
        set(key, value) {
            try {
                localStorage.setItem(`global_var_${key}`, String(value));
                return true;
            } catch (error) {
                console.error(`localStorage设置失败: ${error.message}`);
                return false;
            }
        },
        
        delete(key) {
            try {
                localStorage.removeItem(`global_var_${key}`);
                return true;
            } catch (error) {
                console.error(`localStorage删除失败: ${error.message}`);
                return false;
            }
        }
    };

    // 全局字符串变量管理器
    const GlobalVarsManager = {
        // 默认字符串变量配置
        defaults: {
            'user_token': '',
            'current_project': '',
            'last_operation': '',
            'factory_no': '',
            'factory_name': '',
            'sub_factory_no': '',
            'sub_factory_name': '',
            'month_str': ''
        },

        // 已知的自定义变量列表（用于Tampermonkey环境）
        knownCustomVars: [],

        // 获取字符串变量
        get(key, defaultValue = '') {
            try {
                if (isTampermonkey) {
                    const value = GM_getValue(`global_var_${key}`, defaultValue);
                    return value || defaultValue;
                } else {
                    return fallbackStorage.get(key, defaultValue);
                }
            } catch (error) {
                this.log(`获取字符串变量 ${key} 失败: ${error.message}`, 'error');
                return defaultValue;
            }
        },

        // 设置字符串变量
        set(key, value) {
            try {
                const stringValue = String(value);
                if (isTampermonkey) {
                    GM_setValue(`global_var_${key}`, stringValue);
                    // 如果是新变量，添加到已知变量列表
                    if (!this.defaults.hasOwnProperty(key) && !this.knownCustomVars.includes(key)) {
                        this.knownCustomVars.push(key);
                        // 保存已知变量列表
                        GM_setValue('global_var_known_custom_vars', JSON.stringify(this.knownCustomVars));
                    }
                } else {
                    fallbackStorage.set(key, stringValue);
                }
                this.log(`设置字符串变量 ${key}: ${stringValue}`, 'success');
                return true;
            } catch (error) {
                this.log(`设置字符串变量 ${key} 失败: ${error.message}`, 'error');
                return false;
            }
        },

        // 删除字符串变量
        delete(key) {
            try {
                if (isTampermonkey) {
                    GM_setValue(`global_var_${key}`, '');
                } else {
                    fallbackStorage.delete(key);
                }
                this.log(`删除字符串变量 ${key}`, 'success');
                return true;
            } catch (error) {
                this.log(`删除字符串变量 ${key} 失败: ${error.message}`, 'error');
                return false;
            }
        },

        // 获取所有字符串变量
        getAll() {
            const result = {};
            
            // 首先添加默认变量
            for (const key in this.defaults) {
                result[key] = this.get(key, this.defaults[key]);
            }
            
            // 然后尝试获取所有已保存的变量（包括非默认变量）
            if (isTampermonkey) {
                // 在Tampermonkey环境中，获取已知的自定义变量
                try {
                    const knownVarsJson = GM_getValue('global_var_known_custom_vars', '[]');
                    const knownVars = JSON.parse(knownVarsJson);
                    this.knownCustomVars = knownVars;
                    
                    for (const key of knownVars) {
                        if (!result.hasOwnProperty(key)) {
                            result[key] = this.get(key, '');
                        }
                    }
                } catch (error) {
                    this.log(`获取已知自定义变量失败: ${error.message}`, 'error');
                }
            } else {
                // 在localStorage环境中，可以尝试获取所有相关键
                try {
                    for (let i = 0; i < localStorage.length; i++) {
                        const key = localStorage.key(i);
                        if (key && key.startsWith('global_var_')) {
                            const varKey = key.replace('global_var_', '');
                            if (!result.hasOwnProperty(varKey)) {
                                result[varKey] = this.get(varKey, '');
                            }
                        }
                    }
                } catch (error) {
                    this.log(`获取所有变量失败: ${error.message}`, 'error');
                }
            }
            
            return result;
        },

        // 重置所有字符串变量
        reset() {
            try {
                for (const key in this.defaults) {
                    if (isTampermonkey) {
                        GM_setValue(`global_var_${key}`, this.defaults[key]);
                    } else {
                        fallbackStorage.set(key, this.defaults[key]);
                    }
                }
                this.log('所有字符串变量已重置为默认值', 'success');
                return true;
            } catch (error) {
                this.log(`重置字符串变量失败: ${error.message}`, 'error');
                return false;
            }
        },

        // 导出所有字符串变量到控制台
        export() {
            const allStrings = this.getAll();
            console.log('=== 全局字符串变量导出 ===');
            console.log(JSON.stringify(allStrings, null, 2));
            return allStrings;
        },

        // 从JSON导入变量
        import(jsonData) {
            try {
                const data = typeof jsonData === 'string' ? JSON.parse(jsonData) : jsonData;
                for (const key in data) {
                    this.set(key, data[key]);
                }
                this.log('全局变量导入成功', 'success');
                return true;
            } catch (error) {
                this.log(`导入全局变量失败: ${error.message}`, 'error');
                return false;
            }
        },

        // 添加自定义变量
        addCustomVar(key, defaultValue = '') {
            if (!this.defaults.hasOwnProperty(key)) {
                this.defaults[key] = defaultValue;
                this.log(`添加自定义变量: ${key}`, 'success');
                return true;
            } else {
                this.log(`变量 ${key} 已存在`, 'warn');
                return false;
            }
        },

        // 日志函数
        log(message, type = 'info') {
            const timestamp = new Date().toLocaleString('zh-CN');
            const logMessage = `[全局变量管理器 ${timestamp}] ${message}`;
            
            switch(type) {
                case 'error':
                    console.error(logMessage);
                    break;
                case 'warn':
                    console.warn(logMessage);
                    break;
                case 'success':
                    console.log(`%c${logMessage}`, 'color: green; font-weight: bold;');
                    break;
                default:
                    console.log(`%c${logMessage}`, 'color: blue;');
            }
        },

        // 创建管理面板
        createPanel() {
            // 移除已存在的面板
            const existingPanel = document.getElementById('global-vars-panel');
            if (existingPanel) {
                existingPanel.remove();
            }

            const panel = document.createElement('div');
            panel.id = 'global-vars-panel';
            panel.className = 'global-vars-panel';
            
            const allVars = this.getAll();
            
            let panelHTML = `
                <h3>全局字符串变量管理</h3>
                <div class="panel-content">
            `;
            
            // 为每个变量创建输入框
            for (const key in allVars) {
                const value = allVars[key];
                const isTextarea = key === 'debug_info' || key === 'custom_note' || key === 'user_preferences' || key === 'temp_data';
                const inputElement = isTextarea ? 
                    `<textarea id="var-${key}" placeholder="请输入${key}">${value}</textarea>` :
                    `<input type="text" id="var-${key}" value="${value}" placeholder="请输入${key}">`;
                
                panelHTML += `
                    <div class="var-item">
                        <label for="var-${key}">${key}:</label>
                        ${inputElement}
                    </div>
                `;
            }
            
            panelHTML += `
                </div>
                <div class="panel-buttons">
                    <button class="save-btn" id="save-global-vars">保存</button>
                    <button class="reset-btn" id="reset-global-vars">重置</button>
                    <button class="export-btn" id="export-global-vars">导出</button>
                    <button class="import-btn" id="import-global-vars">导入</button>
                    <button class="close-btn" id="close-global-vars">关闭</button>
                </div>
            `;
            
            panel.innerHTML = panelHTML;
            document.body.appendChild(panel);
            
            // 绑定事件处理函数
            const manager = this; // 保存this引用
            
            document.getElementById('save-global-vars').addEventListener('click', function() {
                for (const key in allVars) {
                    const input = document.getElementById(`var-${key}`);
                    if (input) {
                        manager.set(key, input.value);
                    }
                }
                alert('变量保存成功！');
            });
            
            document.getElementById('reset-global-vars').addEventListener('click', function() {
                if (confirm('确定要重置所有变量为默认值吗？')) {
                    manager.reset();
                    manager.closePanel();
                    manager.createPanel();
                }
            });
            
            document.getElementById('export-global-vars').addEventListener('click', function() {
                manager.export();
                alert('变量已导出到控制台，请按F12查看');
            });
            
            document.getElementById('import-global-vars').addEventListener('click', function() {
                const jsonData = prompt('请输入要导入的JSON数据:');
                if (jsonData) {
                    manager.import(jsonData);
                    manager.closePanel();
                    manager.createPanel();
                }
            });
            
            document.getElementById('close-global-vars').addEventListener('click', function() {
                manager.closePanel();
            });
        },

        // 关闭面板
        closePanel() {
            const panel = document.getElementById('global-vars-panel');
            if (panel) {
                panel.remove();
            }
        },

        // 添加样式
        addStyles() {
            const styles = `
                .global-vars-panel {
                    position: fixed;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%);
                    background: white;
                    border: 2px solid #3742fa;
                    border-radius: 8px;
                    padding: 20px;
                    z-index: 10000;
                    max-width: 600px;
                    max-height: 80vh;
                    overflow-y: auto;
                    box-shadow: 0 4px 20px rgba(0,0,0,0.3);
                    font-family: Arial, sans-serif;
                }
                
                .global-vars-panel h3 {
                    margin: 0 0 15px 0;
                    color: #3742fa;
                    text-align: center;
                    font-size: 18px;
                }
                
                .global-vars-panel .panel-content {
                    max-height: 400px;
                    overflow-y: auto;
                }
                
                .global-vars-panel .var-item {
                    margin-bottom: 15px;
                }
                
                .global-vars-panel label {
                    display: block;
                    margin-bottom: 5px;
                    font-weight: bold;
                    color: #2f3542;
                    font-size: 14px;
                }
                
                .global-vars-panel input, .global-vars-panel textarea {
                    width: 100%;
                    padding: 8px;
                    border: 1px solid #ddd;
                    border-radius: 4px;
                    font-size: 14px;
                    box-sizing: border-box;
                }
                
                .global-vars-panel textarea {
                    height: 60px;
                    resize: vertical;
                }
                
                .global-vars-panel .panel-buttons {
                    text-align: center;
                    margin-top: 20px;
                    padding-top: 15px;
                    border-top: 1px solid #eee;
                }
                
                .global-vars-panel button {
                    margin: 0 5px;
                    padding: 8px 16px;
                    border: none;
                    border-radius: 4px;
                    cursor: pointer;
                    font-size: 14px;
                    transition: background-color 0.3s;
                }
                
                .global-vars-panel .save-btn {
                    background-color: #2ed573;
                    color: white;
                }
                
                .global-vars-panel .save-btn:hover {
                    background-color: #26d0ce;
                }
                
                .global-vars-panel .reset-btn {
                    background-color: #ff4757;
                    color: white;
                }
                
                .global-vars-panel .reset-btn:hover {
                    background-color: #ff3742;
                }
                
                .global-vars-panel .close-btn {
                    background-color: #747d8c;
                    color: white;
                }
                
                .global-vars-panel .close-btn:hover {
                    background-color: #57606f;
                }
                
                .global-vars-panel .export-btn {
                    background-color: #3742fa;
                    color: white;
                }
                
                .global-vars-panel .export-btn:hover {
                    background-color: #2f3542;
                }
                
                .global-vars-panel .import-btn {
                    background-color: #ffa502;
                    color: white;
                }
                
                .global-vars-panel .import-btn:hover {
                    background-color: #ff9500;
                }
                
                .global-vars-btn {
                    position: fixed;
                    top: 20px;
                    right: 20px;
                    background-color: #3742fa;
                    color: white;
                    border: none;
                    padding: 10px 15px;
                    border-radius: 5px;
                    cursor: pointer;
                    font-size: 14px;
                    z-index: 9999;
                    box-shadow: 0 2px 10px rgba(0,0,0,0.2);
                    transition: background-color 0.3s;
                }
                
                .global-vars-btn:hover {
                    background-color: #2f3542;
                }
            `;
            
            const styleElement = document.createElement('style');
            styleElement.textContent = styles;
            document.head.appendChild(styleElement);
        },

        // 创建悬浮按钮
        createFloatingButton() {
            const existingBtn = document.getElementById('global-vars-floating-btn');
            if (existingBtn) {
                existingBtn.remove();
            }

            const button = document.createElement('button');
            button.id = 'global-vars-floating-btn';
            button.className = 'global-vars-btn';
            button.textContent = '变量管理';
            button.title = '全局变量管理器';
            
            button.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                this.createPanel();
            });

            document.body.appendChild(button);
        },

        // 初始化
        init() {
            this.addStyles();
            this.createFloatingButton();
            
            // 暴露到全局作用域
            window.GlobalVarsManager = this;
            
            // 输出环境信息
            if (isTampermonkey) {
                this.log('运行环境: Tampermonkey (使用GM存储)', 'success');
            } else {
                this.log('运行环境: 普通网页 (使用localStorage)', 'warn');
            }
            
            this.log('全局变量管理器初始化完成', 'success');
            this.log('使用方法: window.GlobalVarsManager.get(key) / set(key, value)', 'info');
        }
    };

    // 自动初始化
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => {
            GlobalVarsManager.init();
        });
    } else {
        GlobalVarsManager.init();
    }

})(); 